﻿// <copyright file="TransmitterService.cs" company="Hallvard Korsgaard">
//  Microsoft Public License (Ms-PL). See license details here: http://enoceannet.codeplex.com/license
// </copyright>
// <author>Hallvard Korsgaard</author>

namespace EnOceanService
{
  using System;
  using System.Collections.Generic;
  using System.Net;
  using System.ServiceModel;
  using System.ServiceModel.Discovery;
  using EnOcean;
  using EnOcean.Radio.Sensor;
  using ServiceContract;

  [ServiceBehavior(Name = "EnOceanTransmitter", Namespace = "http://enoceannet.codeplex.com/EnOceanTransmitter/v1")]
  public class TransmitterService : IEnOceanTransmitter
  {
    private static ServiceHost host;

    public IEnumerable<long> GetBaseIds()
    {
      return StcEthernetBroker.GetBaseIds();
    }

    public void SendTelegram(byte[] telegram)
    {
      Telegram t;

      if (telegram != null)
      {
        t = Telegram.Parse(telegram);

        if (t is SensorTelegram)
        {
          StcEthernetBroker.Send((SensorTelegram)t);
        }
        else
        {
          throw new ArgumentException("Unsupported telegram type.");
        }
      }
    }

    internal static void Start()
    {
      Uri address;
      ServiceDiscoveryBehavior sdb;

      address = new Uri("http://" + Dns.GetHostName() + "/EnOceanTransmitter/" + Guid.NewGuid().ToString());

      host = new ServiceHost(typeof(TransmitterService));
      host.AddServiceEndpoint(typeof(IEnOceanTransmitter), new BasicHttpBinding() { Namespace = "http://enoceannet.codeplex.com/EnOceanTransmitter/v1" }, address);
      host.AddServiceEndpoint(new UdpDiscoveryEndpoint() { IsSystemEndpoint = true });

      sdb = new ServiceDiscoveryBehavior();
      sdb.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint() { IsSystemEndpoint = true });

      host.Description.Behaviors.Add(sdb);
      host.Open();
    }

    internal static void Stop()
    {
      host.Close();
    }
  }
}
